package com.example.homework.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.homework.adapters.PhotosPagingSource
import com.example.homework.api.MarsPhotosService
import com.example.homework.models.Photo
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {
    private val _photosMutableStateFlow: MutableStateFlow<List<Photo>> =
        MutableStateFlow<List<Photo>>(listOf())
    val photosFlow: Flow<List<Photo>> = _photosMutableStateFlow.asStateFlow()
    val pagedPhotos:Flow<PagingData<Photo>> = Pager(
        config = PagingConfig(25),
        pagingSourceFactory = {PhotosPagingSource()}
    ).flow.cachedIn(viewModelScope)

    init {
        loadData()
    }

    fun loadData(page: Int = 0) {
        viewModelScope.launch {
            _photosMutableStateFlow.value = MarsPhotosService.getPhotos(page)
        }
    }
}